package io.xxx.xbutler.core.get;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.client.PromotionClient;
import io.xxx.xbutler.common.RedisKeys;
import io.xxx.xbutler.domain.FavoriteProduct;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.Receiver;
import io.xxx.xbutler.domain.task.TaskItem;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@Component
public class FavoriteProductGetter implements ContentGetter {

    @Resource
    private PromotionClient promotionClient;

    @Resource
    private RedissonClient redissonClient;

    @Value("{mini-program.page-path.product:/pages/product/detail}")
    private String productPagePath;

    @Override
    public void replaceContent(PushContext context) {
        LocalDate now = LocalDate.now();

        Receiver receiver = context.getReceiver();
        Long storeId = receiver.getStoreId();
        if (storeId == null) {
            return;
        }
        List<TaskItem> taskItems = context.getTaskItems();
        for (TaskItem taskItem : taskItems) {
            if (taskItem.getContentType() == null) {
                continue;
            }
            if (!taskItem.isFavoriteProduct()) {
                continue;
            }

            RSet<String> favoriteProductsSet = redissonClient.getSet(RedisKeys.favoriteProducts(storeId, now));
            String cache = favoriteProductsSet.removeRandom();
            if (!StringUtils.hasText(cache)) {
                List<FavoriteProduct> favoriteProducts = promotionClient.getFavoriteProducts(storeId);
                List<String> data = favoriteProducts.stream()
                        .map(JSON::toJSONString)
                        .toList();
                favoriteProductsSet.addAll(data);
            }
            FavoriteProduct favoriteProduct = JSON.parseObject(cache, FavoriteProduct.class);
            String pagePath = UriComponentsBuilder.fromPath(productPagePath)
                    .queryParam("skuSn", favoriteProduct.getSkuSn())
                    .toUriString();
            JSONObject content = ContentGetter.buildMiniProgram(favoriteProduct.getName(), favoriteProduct.getImage(), pagePath);
            taskItem.setContent(content);
        }
    }
}
